<?php


namespace app\api\controller\v14;


use app\api\controller\v2\Auth;
use app\common\cachemodel\Goods as GoodsCacheModel;
use app\common\lib\Util;
use Exception;

/**
 * @version 1.9.8
 * Class Goods
 * @package app\api\controller\v14
 */
class Goods extends Auth
{
    protected $notice = [
        1 => '以下所有时间均为东八区哦',
        2 => '下单前请务必核对好购买信息',
        3 => '下单前请务必核对好购买信息',
        4 => '下单前请务必核对好购买信息',
        5 => '下单前请务必核对好购买信息',
        6 => '下单前请务必核对好购买信息',
        7 => '下单前请务必核对好购买信息',
        8 => '下单前请务必核对好购买信息',
    ];

    /**
     * 获取商品信息
     * @throws Exception
     */
    public function read()
    {
        $type = input('param.type/d', 0);
        if (!$type)
        {
            return show(config('code.error'), '未知的商品');
        }
        $gid = input('param.gid/d', 0);
        $rid = input('param.rid/d', 0);
        $rid2 = input('param.rid2/d', 0);
        $now_time = time();
        $start_time = input('param.start_time/s', '');
        //检验请求参数
        $res = $this->checkReadParam(['type' => $type, 'gid' => $gid, 'rid' => $rid, 'start_time' => $start_time]);
        if ($res !== true)
        {
            return show(config('code.error'), $res);
        }
        $GoodsCacheModel = new GoodsCacheModel();
        $goods = $GoodsCacheModel->GoodsTypeInfo($type);
        if ($goods)
        {
            $goods_info = $GoodsCacheModel->resetGoodsInfo($this, $type, $goods, $rid, $rid2, $start_time, $gid);
            // TODO 学业报告临时活动
            if ((int)$type === 7 && $now_time >= 1595498400 && $now_time <= 1599321599)
            {
                $goods_info['notice'] = '单独解锁学业报告才能享受九折优惠哦';
            } else
            {
                $goods_info['notice'] = $this->notice[$type];
            }
            return show(config('code.success'), '获取成功', $goods_info);
        }
        return show(config('code.error'), '商品不存在');
    }

    /**
     * 检测获取商品信息接口请求参数是否正确
     * @param $param
     * @return bool|string
     * @throws \app\common\lib\exception\ApiException
     */
    private function checkReadParam($param)
    {
        switch (true)
        {
            case !in_array($param['type'], [1, 2, 3, 4, 5, 6, 7, 8], true):
                $msg = '未知的商品';
                break;
            case $param['type'] === 6 && !$param['gid']:
                $msg = '缺少商品参数';
                break;
            case in_array($param['type'], [5, 7], true) && !$param['rid']:
                $msg = '档案未知';
                break;
//            case in_array($param['type'], [2, 3, 4], true) && !$param['start_time']:
//                $msg = '未选择时间';
//                break;
            default :
                $msg = true;
                break;
        }
        //检测时间格式
        if ($param['start_time'])
        {
            Util::FormatFortuneTime($param['type'], $param['start_time']);
        }
        return $msg;

    }
}
